import 'dart:convert';
import 'package:flutter/services.dart';
//import 'package:http/http.dart' as http;
import 'package:sync_http/sync_http.dart';
import 'package:date_format/date_format.dart';
import 'candlesticks.dart';
//import 'package:k_chart/flutter_k_chart.dart';

class DataApi {
  static String get_day_kline(String code, int start_date, int end_date,
      [String fields = '']) {
        print('### code:$code');
    Map<String, dynamic> req = {
      'token': '951e1bbba0020a264921d7202a3d4dba4b014479f50cca5286d33f45',
      'api_name': 'daily',
      'params': {
        'ts_code': code,
        'start_date': start_date.toString(),
        'end_date': end_date.toString(),
      },
      //'fields':fields
    };

        print('### code:$code $start_date $end_date');

    var request = SyncHttpClient.postUrl(Uri.http('api.tushare.pro', '/'));
      request.write(jsonEncode(req));
      var response = request.close();
      if(200 != response.statusCode)
      {
      print('Request failed with status: ${response.statusCode}.');
      return '';
      }

    //var url = Uri.parse('http://api.tushare.pro/');
    //var response = http.post(url, body: jsonEncode(req));
        print('### ----- code:$code $start_date $end_date');
    //print('Response status: ${response.statusCode}');
    //      print('Response body: ${response.body}');
    if (response.statusCode == 200) {
      return response.body!;
    } else {
      print('Request failed with status: ${response.statusCode}.');
    }

    return '';
  }

  static List<CandleData> parseCandleDataList(String body) {
    List<CandleData> result = [];
    var jsonResponse = jsonDecode(body) as Map<String, dynamic>;
    var code = jsonResponse['code'] as int;
    var msg = jsonResponse['msg'];
    if(code != 0)
    {
      print('### error: $code $msg');
      return result;
    }
   var fields =<String>[];
   for(var v in jsonResponse['data']['fields']){
    fields.add(v.toString());
   }
   print('### fields: $fields');
   int tidx = fields.indexOf('trade_date');
   int oidx = fields.indexOf('open');
   int hidx = fields.indexOf('high');
   int lidx = fields.indexOf('low');
   int cidx = fields.indexOf('close');
   int vidx = fields.indexOf('vol');
   print('#### $tidx $oidx $hidx $lidx $cidx $vidx' );
    var items = jsonResponse['data']['items'] as List<dynamic>;
    result = items
        .map((row) => CandleData(
              timestamp: DateTime.parse(row[1].toString()).millisecondsSinceEpoch,
              open: row[oidx]?.toDouble(),
              high: row[hidx]?.toDouble(),
              low: row[lidx]?.toDouble(),
              close: row[cidx]?.toDouble(),
              volume: row[vidx]?.toDouble(),
              //amount: 0.0,
            ))
        .toList();
   print('#### size:${result.length} ${result[0]} $tidx $oidx $hidx $lidx $cidx $vidx' );
    return result;
  }
}
